import socket
import sys
import platform
import os
import time
import threading
import requests
from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn
import uuid
import csv
import json

live_ip = 0
all_ip = []

class HTTPHandler(SimpleHTTPRequestHandler):
	def translate_path(self, path):
		path = SimpleHTTPRequestHandler.translate_path(self, path)
		relpath = os.path.relpath(path, os.getcwd())
		fullpath = os.path.join(self.server.base_path, relpath)
		return fullpath

class ThreadHTTPServer(ThreadingMixIn, HTTPServer):
	def do_POST(self):
		req_datas = self.rfile.read(int(self.headers['content-length']))
		datas = req_datas.decode('utf-8')
		datas = json.loads(datas)

def get_os():
	now_os = platform.system()
	if now_os == 'Windows':
		return 'n'
	else:
		return 'c'

def find_local_ip():
	myname = socket.getfqdn(socket.gethostname())
	myaddr = socket.gethostbyname(myname)
	return myaddr

def ping_ip(ip_str):
	global live_ip
	cmd = ['ping ', "-{op} ".format(op=get_os()), "1 ", ip_str]
	output = os.popen("".join(cmd)).readlines()
	for line in output:
		if str(line).upper().find('TTL') >= 0:
			if not ip_str in all_ip:
				all_ip.append(ip_str)
				live_ip += 1
			break

def find_ip(ip_prefix):
	threads = []
	for i in range(1, 256):
		ip = "%s.%s" % (ip_prefix, i)
		threads.append(threading.Thread(target=ping_ip, args={ip, }))
	for t in threads:
		t.start()
	for t in threads:
		t.join()

def get_all_ip():
	addr = find_local_ip()
	args = "".join(addr)
	ip_pre = ".".join(args.split('.')[:-1])
	find_ip(ip_pre)
	return live_ip, all_ip

def get_mac_address():
	mac_address = uuid.UUID(int=uuid.getnode()).hex[-12:].upper()
	mac_address = '-'.join([mac_address[i:i+2] for i in range(0, 11, 2)])
	return mac_address

def main():
	# 目前的思路是这样的
	# 先获取所有IP
	# 然后再通过http.server和requests来判断是否有开启我们的SLST

	# 功能：获取聊天文件
	# 返回值：
	def get_csv_data(file_path):
		with open(file_path) as csv_data:
			csv_reader = csv.reader(csv_data, delimiter=',')
			return csv_reader

	online_now = [] # 所有在线人员
	# 先指定端口号
	port = 18435

	# 获取文件存放的路径
	file_working_path = ''
	file_working_path = os.path.join(os.environ['HOME'], '.stsl')
	if not os.path.exists(file_working_path): # 如果目录不存在
		os.makedirs(file_working_path) # 那就创建

	# 启动服务器
	now_working_path = os.getcwd()
	os.chdir(file_working_path) # 先临时将工作目录切到文件所存储的地方
	httpd = ThreadHTTPServer(('0.0.0.0', port), SimpleHTTPRequestHandler)
	httpd.serve_forever()
	os.chdir(now_working_path)

	while True:
		# 先获取所有IP
		ip_num, all_ip = get_all_ip()

		# 对每个IP都进行检查，看看是否有开启服务器
		for ip in all_ip:
			try:
				now_get = request.get('http://' + ip + ':' + str(port))
			except: # 抛出异常说明木有开放这个端口
				if ip in online_now: # 如果IP在在线人员列表里的话
					online_now.remove(ip) # 很好，现在不在了
				continue

			if not ip in online_now:
				online_now.append(ip) # 如果没有在在线列表里，那么就进去

		# 接下来要读取储存在 ~/.slst/talk 的数据库，但是我要休息了
		# 考虑到部分场景可能IP会频繁更换，所以通过mac地址标记

if __name__ == '__main__':
	main()